<template>
  <div class="basiceinformation-container">
    <div class="project-body marginb-15">
      <el-form ref="form" label-position="right" size="small" label-width="100px" :model="formModel">
        <el-row style="margin: 0px" :gutter="15">
          <el-col :span="12">
            <el-form-item style="width: 100%" label="项目编号:">
              <el-input v-model="formModel.projectPointCode" :disabled="isdisabled" placeholder="自动生成编号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="项目图片:">
              <base-upload :formType="formType" v-model="formModel.picUrl" @change="changeImg"></base-upload>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label=" 项目类型:" prop="projectPointTypeId">
              <el-select class="width-100" v-model="formModel.projectPointTypeId" placeholder="请选择项目点类型">
                <el-option v-for="item in projectTypeOption" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目点名称:" prop="projectPointName">
              <el-input v-model="formModel.projectPointName" placeholder="请输入项目点名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="所属区域:">
              <select-address v-model="region" @change="changeRegin"></select-address>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目地址:" prop="projectAddress" width="50%">
              <el-input v-model="formModel.projectAddress" placeholder="请输入项目地址"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人:" prop="projectDirector">
              <el-input v-model="formModel.projectDirector" placeholder="请输入负责人名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话:">
              <el-input v-model="formModel.directorPhone" placeholder="请输入联系电话"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="所属单位:" prop="deptId">
              <treeselect v-model="formModel.deptId" :options="deptOptions" :normalizer="normalizer" placeholder="选择上级部门" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="排序:" prop="sort">
              <el-input-number class="width-100" controls-position="right" v-model="formModel.sort" :min="0"></el-input-number>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="经度:" prop="lng">
              <div class="width-100">
                <el-input v-model="formModel.lng" placeholder="请选择经度"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="维度:" prop="lat">
              <div class="width-100">
                <el-input v-model="formModel.lat" placeholder="请选择经度"></el-input>
              </div>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="项目点状态:">
              <el-select class="width-100" v-model="formModel.status" placeholder="状态">
                <el-option v-for="item in porjectState" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="简介:" prop="remark">
              <el-input style="min-height: 200px" type="textarea" :autosize="{ minRows: 2, maxRows: 6 }" v-model="formModel.remark" placeholder="请输入内容"></el-input>
            </el-form-item>
          </el-col>

        </el-row>
      </el-form>
    </div>
    <!-- 地图弹窗 -->
    <el-dialog class="m_dialog" title="请选择经纬度" :visible.sync="isVisibleMap" width="800" append-to-body :before-close="Lowercancel" :close-on-click-modal="false">
      <div class="content" style="position: relative">
        <div class="mapDiv" ref="map" style="width: 100%; height: 466px"></div>
        <div class="map-Contern">
          <el-form class="map-form" size="small" ref="mapForm" :model="mapForm" label-width="0">
            <el-form-item label="">
              <el-input v-model="mapForm.mapSearch" placeholder="搜索地区">
                <template slot="suffix">
                  <i class="el-icon-search" @click="mapSearchFn"></i>
                </template>
              </el-input>
            </el-form-item>
            <el-form-item label="">
              <span style="color: #8fabbf">经纬度</span>
              <el-input v-model="mapForm.maplnglat" placeholder=""> </el-input>
            </el-form-item>
            <el-form-item label="">
              <span style="color: #8fabbf">地址</span>
              <el-input v-model="mapForm.mapaddress" placeholder="请选择地址"></el-input>
            </el-form-item>
          </el-form>
          <div slot="footer" class="map-footer-btn">
            <el-button @click="Lowercancel()" class="btn_cancel">取 消</el-button>
            <el-button type="primary" @click="mapSubmitForm" class="btn_primary">确 定</el-button>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import request from "@/utils/request";
import { addProjectPointControl, updateProjectPointControl, listDept, getProjectPointTypeList, } from '@/api'
import { handleTree } from '@/utils/ruoyi'

import Map from "ol/Map";
import View from "ol/View";
// import OSM from 'ol/source/OSM';
import XYZ from "ol/source/XYZ";
// import TileLayer from 'ol/layer/Tile';
import { getProjectPointControl, getRegion, listRegion, getCommonConfig } from "@/api";
import SelectAddress from "@/components/SelectAddress";

// 点位引用
import Feature from "ol/Feature.js";
import Point from "ol/geom/Point.js";
import { Circle, Fill, Icon, Stroke, Style, Text } from "ol/style.js";
import { OGCMapTile, Vector as VectorSource } from "ol/source.js";
import { Tile as TileLayer, Vector as VectorLayer } from "ol/layer.js";
// 地图点击获得经纬度
export default {
  data () {
    return {
      formType:'basicInformation',
      // 地图表单
      mapForm: {
        mapSearch: undefined,
        maplnglat: undefined,
        mapaddress: undefined,
      },
      // 表单
      formModel: {
      },
      // 部门树选项
      deptOptions: [],
      // 项目类型
      projectTypeOption: [],
      isdisabled: true,
      // 父组件传递过来的值
      rowinfo: this.rowData,
      // 地图
      map: null,
      // 是否可见地图
      isVisibleMap: false,
      // 天地图token
      mapToken: "f01023d9e7977aa8946e0137daf05a2b",
      // 地图矢量图层源
      vectorSource: undefined,
      // 地图点位图片样式
      iconStyle: undefined,
      // 项目点状态
      porjectState: [
        {
          label: '有效',
          value: '0',
        },
        {
          label: '无效',
          value: '1',
        },
        {
          label: '演示',
          value: '2',
        },
        {
          label: '勿扰',
          value: '3',
        },
      ],
      // 当前项目点ID
      curreentProjectPointId: '',
      // 所属区域
      region : ""
      // tempArr: [],
    };
  },
  computed: {},
  created () {
    console.log('created')
  },
  methods: {
    handleChange (value) {
      console.log(value);
    },
    selectCoordinate () {
      this.isVisibleMap = true;
      (this.mapForm = {
        mapSearch: undefined,
        maplnglat: undefined,
        mapaddress: undefined,
      }),
        this.initMap();
      // 初始化 Map 并在 Vue 组件的 mounted 钩子中设置它
    },
    // 弹窗-取消
    Lowercancel () {
      this.isVisibleMap = false;
    },
    show (data = {},region) {
      this.resetFrom()
      this.formModel = JSON.parse(JSON.stringify(data))
      this.region = region
      console.log(this.formModel + '2333')
    },
    handleSubmit () {
      try {
        this.$refs.form.validate(async valid => {
          if (valid) {
            const isAddOperation = this.formModel.projectPointId === undefined
            let message = isAddOperation ? '新增成功' : '修改成功'
            let method = isAddOperation ? addProjectPointControl : updateProjectPointControl
            const response = await method(this.formModel)
            if (response.code === 200) {
              if (isAddOperation) {
                const { projectPointId, projectPointName } = response.data
                this.formModel.projectPointId = projectPointId
                const projectPointInfo = {
                  projectPointId: projectPointId,
                  projectPointName: projectPointName
                }
                this.$emit('success', projectPointInfo)
              }
              this.$emit('success', 'update')
              this.$message.success(message)
            }
          } else {
            return false;
          }
        })/*  */
      } catch (error) { }
    },
    // 重置form表单             
    resetFrom () {
      this.formModel = {
        areaId: undefined, // 区县ID
        cityId: undefined, // 市区ID
        deptId: undefined, // 所属单位ID(即是部门ID)
        directorPhone: '', // 项目负责人电话
        lat: undefined, // 纬度
        lng: undefined,  // 经度
        picUrl: undefined, // 项目图片
        picUrlStr:undefined,
        projectAddress: undefined, // 项目点地址
        projectDirector: undefined, // 项目负责人姓名
        projectPointName: undefined, // 项目点名称
        projectPointTypeId: 0, // 项目点类型ID
        provinceId: 0, // 省份ID
        remark: undefined, // 简介
        sort: 0, // 排序(值越小排越前面)
        status: undefined // 状态 0有效 1无效 2演示 3勿扰
      }
      this.$refs.form.resetFields()
    },
    // 项目点图片修改
    changeImg(item) {
      console.log(item,'项目点图片修改')
        this.formModel.picUrl = item
        // this.formModel.picUrl = ''
    },
    // 地图初始化
    initMap () {
      this.$nextTick(() => {
        // 创建一个矢量要素
        const iconFeature = new Feature({
          geometry: new Point([117.01,25.09]),
        });
        // 定义图片样式
        this.iconStyle = new Style({
          image: new Icon({
            anchor: [0.5, 1],
            src: "https://openlayers.org/en/latest/examples/data/icon.png",
          }),
        });
        // 设置要素样式
        iconFeature.setStyle(this.iconStyle);

        // 创建矢量数据源和图层
        this.vectorSource = new VectorSource({
          features: [iconFeature],
        });
        const vectorLayer = new VectorLayer({
          source: this.vectorSource,
        });
        this.map = new Map({
          layers: [
            new TileLayer({
              source: new XYZ({
                url: `http://t0.tianditu.gov.cn/vec_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=vec&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
              }),
              // setStyle: "black",
            }),
            new TileLayer({
              source: new XYZ({
                url: `http://t0.tianditu.gov.cn/cva_w/wmts?SERVICE=WMTS&REQUEST=GetTile&VERSION=1.0.0&LAYER=cva&STYLE=default&TILEMATRIXSET=w&FORMAT=tiles&TILEMATRIX={z}&TILEROW={y}&TILECOL={x}&tk=${this.mapToken}`,
              }),
              // setStyle: "black",
            }),
            vectorLayer,
          ],
          view: new View({
            center: [118.1163, 24.4673],
            zoom: 12,
            projection: "EPSG:4326",
          }),
          // 使用 Vue 的 ref 来引用 DOM 元素
          target: this.$refs.map,
        });
        this.map.addEventListener("click", this.MapClick);
      });
    },
    // 地图点击事件
    MapClick (e) {
      let coordinate = e.coordinate;
      console.log(coordinate);
      this.getGeocoderAddress(coordinate[0], coordinate[1]).then((res) => {
        this.mapForm.mapaddress = res.result.formatted_address;
      });
      // 创建一个新的图标要素
      this.mapForm.maplnglat = coordinate.join("/");
      let newIconFeature = new Feature({
        geometry: new Point(coordinate),
      });
      newIconFeature.setStyle(this.iconStyle);
      // 清除之前的图标要素
      this.vectorSource.clear();
      // 添加新的图标要素
      this.vectorSource.addFeature(newIconFeature);
    },
    // 根据地图坐标获取具体地址
    getGeocoderAddress (lon, lat) {
      return request({
        url: `/geocoder?postStr={'lon':${lon},'lat':${lat},'ver':1}&type=geocode&tk=${this.mapToken}`,
        method: "post",
        type: "map",
      });
    },
    // 地图搜索功能
    mapSearchFn () {
      let keyWord = this.mapForm.mapSearch;
      this.getGeocoderLonLat(keyWord).then((res) => {
        let newIconFeature = new Feature({
          geometry: new Point([res.location.lon, res.location.lat]),
        });
        newIconFeature.setStyle(this.iconStyle);
        this.vectorSource.clear();
        console.log(res.location.lon, res.location.lat);
        this.map.getView().setCenter([res.location.lon, res.location.lat]);
        this.map.getView().setZoom(12);
        // 添加新的图标要素
        this.vectorSource.addFeature(newIconFeature);
        this.mapForm.maplnglat = res.location.lon + "," + res.location.lat;
      });
    },
    // 根据地址获取对应的地图坐标
    getGeocoderLonLat (keyWord) {
      return request({
        url: `/geocoder?ds={'keyWord':"${keyWord}"}&tk=${this.mapToken}`,
        method: "post",
        type: "map",
      });
    },
    // 地图确定按钮
    mapSubmitForm () {
      let tempLonLatArr = this.mapForm.maplnglat;
      this.formModel.lng = tempLonLatArr.split("/")[0];
      this.formModel.lat = tempLonLatArr.split("/")[1];
      this.isVisibleMap = false;
    },
    // 选择地址
    changeRegin (regin) {
      this.formModel.provinceId = regin.p
      this.formModel.cityId = regin.c
      this.formModel.areaId = regin.a
    },
    /** 转换部门数据结构 */
    normalizer (node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.deptId,
        label: node.deptName,
        children: node.children
      };
    },
    listDept () {
      listDept().then(response => {
        this.deptOptions = handleTree(response.data, "deptId");
      });
    },
    getProjectTypeOption () {
      getProjectPointTypeList().then(res => {
        let tempArr = []
        // const resp = response.data
        // for (const item of response.data) {
        //   tempArr.push({
        //     label: item.projectPointTypeName,
        //     value: item.projectPointTypeId
        //   })
        // }
        res.data.forEach(item => {
          tempArr.push({
            label: item.projectPointTypeName,
            value: item.projectPointTypeId
          })
        })
        this.projectTypeOption = tempArr
      })
    },
  },
  created () {
    this.listDept()
    this.getProjectTypeOption()
  },
  mounted () { },
  components: {
    SelectAddress,
  },
};
</script>

<style lang="less" scoped>
@dialog-height: 860px;
.basiceinformation-container {
  height: calc(@dialog-height - 230px);
  overflow: auto;
  .project-body {
    padding: 0 15px;
    height: 100%;
  }
}

// 天地图样式？
/deep/ .ol-zoom.ol-unselectable.ol-control {
  display: none;
}

/deep/ .ol-rotate.ol-unselectable.ol-control.ol-hidden {
  display: none;
}

/deep/ .map-Contern {
  .map-form {
    padding: 24px;

    .el-form-item--small.el-form-item {
      margin-bottom: 12px;
    }
  }

  .map-footer-btn {
    display: flex;
    justify-content: flex-end;
    align-items: center;
    padding-bottom: 10px;
  }
}

/deep/ .map-Contern {
  position: absolute;
  top: 0;
  right: 0;
  background: rgba(19, 21, 26, 0.6);
}
</style>
